<template>
  <div>
    <div class="nav">
      <div>企业管理</div>
      <div style="margin-left: auto; display: flex; align-items: center">
        <div v-if="taxpayerNum">税号：{{ taxpayerNum }}</div>
        <div v-if="deptName" style="margin-left: 20px">
          当前企业：{{ deptName }}
        </div>
        <div class="right-menu">
          <el-dropdown
            class="avatar-container right-menu-item hover-effect"
            trigger="click"
          >
            <div class="avatar-wrapper">
              <img src="@/assets/defaultAvatar.png" class="user-avatar" />
              <i class="el-icon-caret-bottom" style="color: #fff" />
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleResetPwd">
                <span>重置密码</span>
              </el-dropdown-item>
              <el-dropdown-item @click.native="logout">
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>
    <div class="main">
      <div class="app-container">
        <el-row :gutter="10">
          <el-col :span="2">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>

          <!-- <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              >批量删除</el-button
            >
          </el-col> -->
          <el-col :span="22">
            <div style="display: flex; justify-content: flex-end">
              <el-form
                :model="queryParams"
                ref="queryForm"
                size="small"
                :inline="true"
                label-width="68px"
              >
                <el-form-item label="企业名称" prop="deptName">
                  <el-input
                    v-model="queryParams.deptName"
                    placeholder="请输入企业名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                  >
                  <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                  >
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="companyList"
          max-height="400"
          @selection-change="handleSelectionChange"
          @row-click="handleCurrentChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="企业名称" align="center" prop="deptName" />
          <el-table-column label="税号" align="center" prop="taxpayerNum" />
          <el-table-column label="创建日期" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div style="margin: 0 auto; width: 200px; margin-top: 100px">
          <el-button style="width: 100%" type="primary" @click="goIndex"
            >进入软件</el-button
          >
        </div>
        <!-- 添加或修改商家管理对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="700px"
          append-to-body
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="公司名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入公司名称" />
            </el-form-item>
            <el-form-item label="税号" prop="taxpayerNum">
              <el-input v-model="form.taxpayerNum" placeholder="请输入税号" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import { resetUserPwd } from "@/api";
import {
  listCompany,
  getInvoiceExpenses,
  delCompany,
  addCompany,
  updateCompany,
} from "@/api/business/company";
export default {
  name: "company",
  data() {
    return {
      companyAllList: [],
      // 日期范围
      dateRange: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商家管理表格数据
      companyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        deptName: null,
      },
      selections: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" },
        ],
        taxpayerNum: [
          { required: true, message: "税号不能为空", trigger: "blur" },
        ],

        city: [{ required: true, message: "地址不能为空", trigger: "change" }],
        address: [
          { required: true, message: "详细地址不能为空", trigger: "blur" },
        ],
      },
      deptName: "",
      taxpayerNum: "",
      selectCompany: {},
    };
  },
  created() {
    if (localStorage.getItem("selectCompany")) {
      this.selectCompany = JSON.parse(localStorage.getItem("selectCompany"));
      this.deptName = this.selectCompany.deptName;
      this.taxpayerNum = this.selectCompany.taxpayerNum;
    }
    this.getList();
    //   this.getAllList();
  },
  methods: {
    /** 查询商家管理列表 */
    getList() {
      this.loading = true;
      listCompany(this.queryParams).then((response) => {
        this.companyList = response.data;
        this.loading = false;
      });
    },
    //全部厂商
    getAllList() {
      listCompany().then((response) => {
        this.companyAllList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: null,
        deptName: null,
        taxpayerNum: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.deptId);
      this.selections = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleCurrentChange(val) {
      this.$refs.multipleTable.toggleRowSelection(val);
    },
    goIndex() {
      if (localStorage.getItem("selectCompany")) {
        if (this.selections.length > 1) {
          this.$modal.msgWarning("请选择一个企业");
          return;
        }
        if (this.selections.length === 1) {
          localStorage.setItem(
            "selectCompany",
            JSON.stringify(this.selections[0])
          );
        }
        this.$router.push("/");
      } else {
        if (this.companyList.length === 0) {
          this.$modal.msgWarning("请添加企业");
          return;
        }
        if (this.selections.length !== 1) {
          this.$modal.msgWarning("请选择一个企业");
          return;
        }
        console.log(this.selections[0]);
        localStorage.setItem(
          "selectCompany",
          JSON.stringify(this.selections[0])
        );
        this.$router.push("/");
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form.deptId = row.deptId;
      this.form.deptName = row.deptName;
      this.form.taxpayerNum = row.taxpayerNum;
      this.open = true;
      this.title = "修改企业";
      // const id = row.id || this.ids;
      // getCompany(id).then((response) => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改商家管理";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.deptId != null) {
            updateCompany(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCompany(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.deptId || this.ids;
      this.$modal
        .confirm("是否确认删除该企业吗？")
        .then(function () {
          return delCompany(ids);
        })
        .then(() => {
          if (this.selectCompany.deptId && ids === this.selectCompany.deptId) {
            localStorage.removeItem("selectCompany");
            this.deptName = "";
            this.taxpayerNum = "";
          }
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    async logout() {
      this.$confirm("确定注销并退出系统吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("LogOut").then(() => {
            location.href = "/";
          });
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/company/export",
        {
          ...this.queryParams,
        },
        `company_${new Date().getTime()}.xlsx`
      );
    },
    handleResetPwd() {
      this.$prompt("请输入新密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      })
        .then(({ value }) => {
          resetUserPwd({ password: value }).then((response) => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
.nav {
  padding: 0 20px;
  box-sizing: border-box;
  width: 100%;
  height: 50px;
  background: #1890ff;
  display: flex;
  align-items: center;
  font-weight: 500;
  font-size: 16px;
  color: #ffffff;
  position: fixed;
  top: 0;
}
.main {
  margin-top: 50px;
}
.app-container {
  padding: 20px 30px;
}
.right-menu {
  /* margin-left: 10px; */
  /* height: 100%;
  line-height: 50px; */
  &:focus {
    outline: none;
  }

  .right-menu-item {
    display: inline-block;
    padding: 0 8px;
    height: 100%;
    font-size: 18px;
    color: #5a5e66;
    vertical-align: text-bottom;

    &.hover-effect {
      cursor: pointer;
      transition: background 0.3s;

      &:hover {
        background: rgba(0, 0, 0, 0.025);
      }
    }
  }

  .avatar-container {
    margin-right: 10px;
    .avatar-wrapper {
      margin-top: 5px;
      position: relative;
      .user-avatar {
        cursor: pointer;
        width: 35px;
        height: 35px;
        border-radius: 10px;
      }

      .el-icon-caret-bottom {
        cursor: pointer;
        position: absolute;
        right: -13px;
        top: 22px;
        font-size: 14px;
      }
    }
  }
}
</style>
